package com.socket.learing.example;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.Inet4Address;
import java.net.Socket;

@Slf4j
public class ClientSocket {

    public static void main(String[] args) throws IOException {
        Socket socket = new Socket(Inet4Address.getLocalHost(), 2000);

        log.info("创建连接，服务器IP：{}，服务器端口：{}", socket.getInetAddress().getHostAddress(), socket.getPort());
        log.info("创建连接，客户端IP：{}，客户端端口：{}", socket.getLocalAddress().getHostAddress(), socket.getLocalPort());

        sendMessage(socket);
    }

    /**
     * 进行消息发送操作
     *
     * @param socket
     */
    public static void sendMessage(Socket socket) throws IOException {
        try (
                InputStreamReader inputStreamReader = new InputStreamReader(System.in);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                PrintStream printStream = new PrintStream(socket.getOutputStream());
                BufferedReader bufferedWriter = new BufferedReader(new InputStreamReader(socket.getInputStream()))
        ) {
            do {
                String message = bufferedReader.readLine();
                if ("bye".equals(message)) {
                    break;
                } else {
                    printStream.println(message);
                }
                String recivie = bufferedWriter.readLine();
                log.info("接收到服务器返回信息：{}", recivie);
            } while (true);
        } catch (Exception e) {
            log.error("异常退出：{}", e);
        } finally {
            socket.close();
        }
    }
}